<template>
  <view class="dream-container">
    <!-- 顶部选项卡 -->
    <view class="dream-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['dream-tab', activeTab === tab.key ? 'active' : '']"
        @click="handleTabChange(tab.key)"
      >
        {{ tab.label }}
      </view>
    </view>
    
    <!-- 梦想大厅 -->
    <view v-if="activeTab === 'dream-hall'" class="dream-content">
      <view class="dream-list" v-if="dreamHallList.length > 0">
        <view 
          v-for="(item, index) in dreamHallList" 
          :key="item.id"
          class="dream-item"
        >
          <view class="dream-title">{{ item.title }}</view>
          <view class="dream-desc">{{ item.content }}</view>
          <view class="dream-time">{{ item.createTime }}</view>
        </view>
      </view>
      <view v-else class="empty-tip">暂无梦想，快来分享你的梦想吧~</view>
    </view>
    
    <!-- 我的梦想 -->
    <view v-else-if="activeTab === 'my-dream'" class="dream-content">
      <!-- 添加梦想按钮 -->
      <view class="add-dream" @click="showAddDreamModal = true">
        <text class="add-icon">+</text>
        <text>添加梦想</text>
      </view>
      
      <view class="dream-list" v-if="myDreamList.length > 0">
        <view 
          v-for="(item, index) in myDreamList" 
          :key="item.id"
          class="dream-item my-dream-item"
        >
          <view class="dream-title">{{ item.title }}</view>
          <view class="dream-desc">{{ item.content }}</view>
          <view class="dream-time">{{ item.createTime }}</view>
          <view class="dream-actions">
            <text class="edit-btn" @click="handleEditDream(item)">编辑</text>
            <text class="delete-btn" @click="handleDeleteDream(item.id)">删除</text>
          </view>
        </view>
      </view>
      <view v-else class="empty-tip">暂无梦想，快来添加你的梦想吧~</view>
    </view>
    
    <!-- 添加/编辑梦想弹窗 -->
    <uni-popup ref="popup" type="dialog">
      <view class="dream-form">
        <view class="form-title">{{ isEdit ? '编辑梦想' : '添加梦想' }}</view>
        <view class="form-item">
          <text class="form-label">标题</text>
          <input 
            class="form-input" 
            v-model="dreamForm.title" 
            placeholder="请输入梦想标题"
          />
        </view>
        <view class="form-item">
          <text class="form-label">内容</text>
          <textarea 
            class="form-textarea" 
            v-model="dreamForm.content" 
            placeholder="请输入梦想内容"
          />
        </view>
        <view class="form-actions">
          <button class="cancel-btn" @click="handleCancelDream">取消</button>
          <button class="confirm-btn" @click="handleSaveDream">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { getDreamHall, getMyDreams, createDream, updateDream, deleteDream, DreamItem } from '@/api/dream';

// 选项卡数据
const tabs = [
  { key: 'dream-hall', label: '梦想大厅' },
  { key: 'my-dream', label: '我的梦想' }
];

// 响应式数据
const activeTab = ref<string>('dream-hall');
const dreamHallList = ref<DreamItem[]>([]);
const myDreamList = ref<DreamItem[]>([]);
const showAddDreamModal = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const currentDreamId = ref<string | number>('');

// 梦想表单
const dreamForm = reactive({
  title: '',
  content: ''
});

// 弹窗引用
const popup = ref<any>(null);

/**
 * 切换选项卡
 */
const handleTabChange = (key: string): void => {
  activeTab.value = key;
  if (key === 'dream-hall') {
    fetchDreamHall();
  } else if (key === 'my-dream') {
    fetchMyDreams();
  }
};

/**
 * 获取梦想大厅数据
 */
const fetchDreamHall = async (): Promise<void> => {
  try {
    const params = {
      page: 1,
      pageSize: 10
    };
    const res = await getDreamHall(params);
    if (res.code === 200) {
      dreamHallList.value = res.data.rows || [];
    }
  } catch (error) {
    console.error('获取梦想大厅失败', error);
    uni.showToast({
      title: '获取梦想大厅失败',
      icon: 'none'
    });
  }
};

/**
 * 获取我的梦想数据
 */
const fetchMyDreams = async (): Promise<void> => {
  try {
    const params = {
      page: 1,
      pageSize: 10
    };
    const res = await getMyDreams(params);
    if (res.code === 200) {
      myDreamList.value = res.data.rows || [];
    }
  } catch (error) {
    console.error('获取我的梦想失败', error);
    uni.showToast({
      title: '获取我的梦想失败',
      icon: 'none'
    });
  }
};

/**
 * 编辑梦想
 */
const handleEditDream = (dream: DreamItem): void => {
  isEdit.value = true;
  currentDreamId.value = dream.id;
  dreamForm.title = dream.title;
  dreamForm.content = dream.content;
  popup.value.open();
};

/**
 * 删除梦想
 */
const handleDeleteDream = async (id: string | number): Promise<void> => {
  try {
    uni.showModal({
      title: '提示',
      content: '确定要删除这个梦想吗？',
      success: async (res) => {
        if (res.confirm) {
          const result = await deleteDream(id);
          if (result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            // 重新获取我的梦想列表
            fetchMyDreams();
          }
        }
      }
    });
  } catch (error) {
    console.error('删除梦想失败', error);
    uni.showToast({
      title: '删除梦想失败',
      icon: 'none'
    });
  }
};

/**
 * 取消添加/编辑梦想
 */
const handleCancelDream = (): void => {
  popup.value.close();
  resetDreamForm();
};

/**
 * 保存梦想
 */
const handleSaveDream = async (): Promise<void> => {
  try {
    // 表单验证
    if (!dreamForm.title.trim()) {
      uni.showToast({
        title: '请输入梦想标题',
        icon: 'none'
      });
      return;
    }
    if (!dreamForm.content.trim()) {
      uni.showToast({
        title: '请输入梦想内容',
        icon: 'none'
      });
      return;
    }
    
    let res;
    if (isEdit.value) {
      // 编辑梦想
      res = await updateDream({
        id: currentDreamId.value,
        title: dreamForm.title,
        content: dreamForm.content
      });
    } else {
      // 添加梦想
      res = await createDream({
        title: dreamForm.title,
        content: dreamForm.content
      });
    }
    
    if (res.code === 200) {
      uni.showToast({
        title: isEdit.value ? '编辑成功' : '添加成功',
        icon: 'success'
      });
      popup.value.close();
      resetDreamForm();
      // 重新获取我的梦想列表
      fetchMyDreams();
    }
  } catch (error) {
    console.error(isEdit.value ? '编辑梦想失败' : '添加梦想失败', error);
    uni.showToast({
      title: isEdit.value ? '编辑梦想失败' : '添加梦想失败',
      icon: 'none'
    });
  }
};

/**
 * 重置梦想表单
 */
const resetDreamForm = (): void => {
  dreamForm.title = '';
  dreamForm.content = '';
  isEdit.value = false;
  currentDreamId.value = '';
};

// 页面加载时获取梦想大厅数据
onMounted(() => {
  fetchDreamHall();
});
</script>

<style>
.dream-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.dream-tabs {
  display: flex;
  background-color: #ffffff;
  border-bottom: 1px solid #eeeeee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.dream-tab {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 32rpx;
  color: #666;
  position: relative;
}

.dream-tab.active {
  color: #007aff;
  font-weight: bold;
}

.dream-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #007aff;
  border-radius: 3rpx;
}

.dream-content {
  flex: 1;
  padding: 30rpx;
  overflow-y: auto;
}

.add-dream {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-icon {
  font-size: 40rpx;
  margin-right: 10rpx;
  color: #007aff;
}

.dream-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.dream-item {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.my-dream-item {
  border-left: 8rpx solid #007aff;
}

.dream-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.dream-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  line-height: 1.5;
}

.dream-time {
  font-size: 24rpx;
  color: #999;
}

.dream-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  gap: 30rpx;
}

.edit-btn, .delete-btn {
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
}

.edit-btn {
  color: #007aff;
  background-color: rgba(0, 122, 255, 0.1);
}

.delete-btn {
  color: #ff3b30;
  background-color: rgba(255, 59, 48, 0.1);
}

.empty-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

.dream-form {
  padding: 30rpx;
  width: 600rpx;
}

.form-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 20rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.form-input, .form-textarea {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.form-textarea {
  height: 200rpx;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
  gap: 20rpx;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  padding: 20rpx 0;
  text-align: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.cancel-btn {
  background-color: #f2f2f2;
  color: #666;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
}
</style>